package org.smartcti.freeswitch.inbound;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.BufferUnderflowException;
import java.nio.channels.ClosedChannelException;

import org.apache.log4j.Logger;
import org.xsocket.MaxReadSizeExceededException;
import org.xsocket.connection.IConnectHandler;
import org.xsocket.connection.IDataHandler;
import org.xsocket.connection.IDisconnectHandler;
import org.xsocket.connection.INonBlockingConnection;

public class EchoHandler implements IDataHandler,IConnectHandler,IDisconnectHandler    {
	
	private static final Logger  logger = Logger.getLogger(EchoHandler.class);

	public boolean onData(INonBlockingConnection nbc) throws IOException,
			BufferUnderflowException, ClosedChannelException,
			MaxReadSizeExceededException {
		   // read the whole logical part or throwing a BufferUnderflowException
	    final String res =nbc.readStringByDelimiter("\n\n");
	    final String result = URLDecoder.decode(res,"UTF-8");
	    
	    
	    logger.debug("event begin:\n"+result+"\nevent end\n");
//	  	if(res.equals("Content-Type: auth/request")){
//	  		StringBuilder commandBuffer = new StringBuilder();
//			commandBuffer.append("auth ClueCon");
//			commandBuffer.append("\n\n");
//			nbc.write(commandBuffer.toString());
//			String tt = nbc.readStringByDelimiter("\n\n");
//			logger.debug("sync :\n"+tt+"\n");
//	  	}

	      return true;
	}

	public boolean onConnect(INonBlockingConnection nbc) throws IOException,
			BufferUnderflowException, MaxReadSizeExceededException {
		System.out.println("onConnect");
		String data = nbc.readStringByDelimiter("\n\n");
	    System.out.println("data is:\n"+data);
		return true;
	}

	public boolean onDisconnect(INonBlockingConnection nbc) throws IOException {
		System.out.println("onDisconnect");
		String data = nbc.readStringByDelimiter("\n\n");
	    System.out.println("data is:\n"+data);
		return true;
	}

	
}
